package com.shketai.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.shketai.entity.Imessage;
import com.shketai.entity.Teacher;
import com.shketai.entity.User;


public class ImessageDao {

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 新增一条站内信
	 * @param imessage
	 * @return
	 */
	public void add(List<Integer> user_ids,String head,String message,int teacher_id){
		if(user_ids.size()>0){
			Session session = sessionFactory.getCurrentSession();
			Date now = new Date();
			
			for (Integer user_id : user_ids) {
				Imessage imessage = new Imessage();
				User user = new User();
				user.setId(user_id);
				imessage.setUser(user);
				Teacher teacher = new Teacher();
				teacher.setId(teacher_id);
				imessage.setTeacher(teacher);
				imessage.setTime(now);
				imessage.setFlag(0);
				imessage.setHead(head);
				imessage.setMessage(message);
				session.save(imessage);
			}
		}
		
	}
	
	
	public List<Imessage> find(int user_id,int page){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Imessage where user_id=?");
		query.setInteger(0, user_id);
		query.setFirstResult((page-1)*10);
		query.setMaxResults(10);
		List<Imessage> list = query.list();
		if(list.size() > 0){
			return list;
		}else{
			return null;
		}
	}
	public int findCount1(int user_id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(*) from Imessage where user_id=?");
		query.setInteger(0, user_id);
		Long total = (Long) query.uniqueResult();
		return total.intValue();
	}
	public void updateFlag(int id){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("update Imessage set flag=1 where  id =" + id);
		System.out.println("dao:trail:" + id);
		//引号id
		query.executeUpdate();
	}
	
	public Imessage findById(int id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Imessage where id=?");
		query.setInteger(0, id);
		List<Imessage> list = query.list();
		Imessage imessage = list.get(0);
		return imessage;
	}
	
	public int delete(Imessage imessage){
		Session session = sessionFactory.getCurrentSession();
		session.delete(imessage);
		return 1;
	}
	
	public int findCount(int user_id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(*) from Imessage where flag=0 and user_id=?");
		query.setInteger(0, user_id);
		Long total = (Long) query.uniqueResult();
		return total.intValue();
	}
}
